const handler = require('sv-handle-res')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 题目列表
  async examList() {
    const {
      from_lib,
      exam_id
    } = this.params

    let examRes

    // 可根据所属的题库: from_lib筛选
    if (from_lib || exam_id) {
      examRes = await db.collection('st-exam-list').where(dbCmd.or({
        "from_lib": dbCmd.eq(from_lib)
      }, {
        "exam_id": dbCmd.eq(exam_id)
      })).orderBy('exam_index', 'asc').get()
    } else {
      examRes = await db.collection('st-exam-list').orderBy('exam_index', 'asc').get()
    }

    return handler.result({
      data: examRes.data,
    })
  },
  // 更新题目
  async examUpdate() {
    const {
      _id,
      exam_id,
    } = this.params

    if (!exam_id) {
      throw handler.result({
        code: 40001
      })
    }

    delete this.params._id // 移除_id字段，_id不参与更新
    const examRes = await db.collection('st-exam-list').doc(_id).update(this.params)

    return handler.result({
      data: examRes,
    })
  },
  // 添加题目
  async examAdd() {
    const {
      from_lib,
      exam_id,
      exam_title,
      exam_type,
      exam_option,
      exam_answer
    } = this.params

    if (!exam_id || !from_lib || !exam_title || !exam_option || !exam_answer ||
      exam_type === null || exam_type === undefined) {
      throw handler.result({
        code: 40001
      })
    }

    const examRes = await db.collection('st-exam-list').add(this.params)

    return handler.result({
      data: examRes,
    })
  },
  // 删除题目
  async examDelete() {
    const {
      exam_id
    } = this.params

    if (!exam_id) {
      throw handler.result({
        code: 40001
      })
    }

    const examRes = await db.collection('st-exam-list').where({
      "exam_id": dbCmd.eq(exam_id)
    }).remove()

    return handler.result({
      data: examRes,
    })
  },
}